import supabase, { supabaseUrl } from './supabase'

export async function getCabins() {
	const { data, error } = await supabase.from('cabins').select('*')

	if (error) {
		throw new Error(error.message)
	}

	return data
}

export async function deleteCabin(id) {
	const { data, error } = await supabase.from('cabins').delete().eq('id', id)

	if (error) {
		throw new Error(error.message)
	}

	return data
}

export async function createEditCabin(cabin, id) {
	const hasImagePath = cabin?.image?.startsWith?.(supabaseUrl)
	const imageName = hasImagePath
		? cabin.image.split('cabin-images/').pop()
		: `${Date.now()}-${cabin?.image?.name?.replaceAll('/', '')}`
	const imagePath = hasImagePath
		? cabin.image
		: `${supabaseUrl}/storage/v1/object/public/cabin-images/${imageName}`

	let query = supabase.from('cabins')

	// CREATE
	if (!id) {
		query = query
			.insert([{ ...cabin, image: imagePath }])
			.select()
			.single()
	}

	// UPDATE
	if (id) {
		query = query.update({ ...cabin, image: imagePath }).eq('id', id)
	}

	const { data, error } = await query

	if (error) {
		console.error(error)
		throw new Error(error.message)
	}

	if (hasImagePath) return;
	const { error: storageError } = await supabase.storage
		.from('cabin-images')
		.upload(imageName, cabin.image)

	if (storageError) {
		console.error(storageError)
		await supabase.from('cabins').delete().eq('id', data.id)
		throw new Error(storageError.message)
	}

	return data
}
